package dao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class BaseDao<T> {
	private Class<T> entityClass;
	private String tableName;
	private Field[] fields;

	public BaseDao() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		entityClass = (Class<T>) type.getActualTypeArguments()[0];// 获取子类信息
		tableName = entityClass.getSimpleName();// 获取表明
		fields = entityClass.getDeclaredFields();// 获取字段名
	}

	/**
	 * 公共的插入方法
	 * 
	 * @param o
	 * @throws SQLException
	 */
	public void insert(T o) throws SQLException {
		/**
		 * 定义SQL语句
		 */
		String sql = "insert into " + tableName + "(";
		for (int i = 0; i < fields.length; i++) {
			if (i < fields.length - 1)
				sql += fields[i].getName() + ",";
			else
				sql += fields[i].getName() + ") values(";
		}
		for (int i = 0; i < fields.length; i++) {
			if (i < fields.length - 1)
				sql += "?,";
			else
				sql += "?)";
		}
		System.out.println(sql);
		// 输出sql（以regions表为例：输出结果：insert into regions(region_id,region_name) values(?,?)）
		Connection conn = Util.getConnection();// 创建连接
		conn.setAutoCommit(false);// 不允许自动提交
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			for (int i = 0; i < fields.length; i++) {
				fields[i].setAccessible(true);// 允许访问私有成员
				pstm.setObject(i + 1, fields[i].get(o));
			}
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conn.commit();// 提交
	}

	/**
	 * 查询
	 * 
	 * 
	 */
	public List<T> foundAll() {
		List<T> list = new ArrayList<>();// 创建存储数列
		String sql = "select * from " + tableName;
		Connection conn = Util.getConnection();// 建立连接
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				T t = entityClass.newInstance();//类的实例化对象
				for (int i = 0; i < fields.length; i++) {
					Object value = rs.getObject(i + 1);
					if (value instanceof BigDecimal) {
						BigDecimal bd = (BigDecimal) value;
						value = bd.intValue();
					} // number类型转换
					fields[i].setAccessible(true);
					fields[i].set(t, value);
				}
				list.add(t);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 
	 * 修改
	 * 
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public void update(Object o, Object id) throws IllegalArgumentException, IllegalAccessException {
		String sql = "update " + tableName + " set " + fields[1].getName() + "= ? where " + fields[0].getName() + "= ?";
		Connection conn = Util.getConnection();
		try {
			PreparedStatement pstm = conn.prepareStatement(sql);
			pstm.setObject(2, id);
			pstm.setObject(1, o);
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除
	 * 
	 */
	public void delete(String sql){
		Connection conn=Util.getConnection();
		try {
			PreparedStatement pstm=conn.prepareStatement(sql);
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
